package game.module.ddz.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.ddz.bean.DdzRoom;
import game.module.ddz.logic.DdzDataManager;
import game.module.offline.bean.PlayerOfflineCache;
import game.module.offline.logic.PlayerOfflineManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageDdz.C2SDdzBackRoomHall;
import lua.LuaMessageDdz.MemberInfo;
import lua.LuaMessageDdz.S2CDdzBackRoomHall;
import lua.LuaMessageDdz.S2CJoinRoom;
import lua.LuaMessageLogin.S2ErrorCode;

@MsgCodeAnn(msgcode = C2SDdzBackRoomHall.id, accessLimit = 500)
public class DdzBackRoomProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(DdzBackRoomProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		int playerId = hero.getId();
		logger.info("ddz back room,playeyId={}", playerId);
		// 是否在房间中
		boolean isInRoom = DdzDataManager.getInstance().isPlayerInRoom(playerId);
		if (!isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// 房间是否存在
		DdzRoom ddzRoom = DdzDataManager.getInstance().getDdzRoomByPlayerId(playerId);
		if (ddzRoom == null) {
			S2ErrorCode respMsg = new S2ErrorCode(104);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// ret
		String room_id = ddzRoom.getUuid();
		S2CDdzBackRoomHall respMsg = new S2CDdzBackRoomHall();
		respMsg.hall_info = new S2CJoinRoom();
		respMsg.hall_info.room_id = room_id;
		respMsg.hall_info.round_count = ddzRoom.getRoundCount();
		respMsg.hall_info.members = new MemberInfo[ddzRoom.getPlayerList().size()];
		List<Integer> playerIdList = ddzRoom.getPlayerList();
		int i = 0;
		for (Integer aPlayerId : playerIdList) {
			PlayerOfflineCache poc = PlayerOfflineManager.getInstance().getPlayerOfflineCache(aPlayerId);
			respMsg.hall_info.members[i++] = new MemberInfo(aPlayerId, poc.getHeadimg(), poc.getLevel(),
					poc.getSex().shortValue(), poc.getName());
		}
		hero.writeAndFlush(respMsg.build(hero.alloc()));
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// null
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// null
	}

}
